/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.mgt.server.service.power.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.github.yulichang.repository.JoinCrudRepository;
import com.iwindplus.boot.domain.constant.CommonConstant;
import com.iwindplus.boot.domain.enums.BizCodeEnum;
import com.iwindplus.boot.domain.enums.EnableStatusEnum;
import com.iwindplus.boot.domain.exception.BizException;
import com.iwindplus.boot.redis.manager.SerialNumManager;
import com.iwindplus.mgt.domain.constant.MgtConstant;
import com.iwindplus.mgt.domain.dto.power.PositionDTO;
import com.iwindplus.mgt.domain.dto.power.PositionEditDTO;
import com.iwindplus.mgt.domain.dto.power.PositionSaveDTO;
import com.iwindplus.mgt.domain.dto.power.PositionSearchDTO;
import com.iwindplus.mgt.domain.enums.MgtCodeEnum;
import com.iwindplus.mgt.domain.enums.MgtCodePrefixEnum;
import com.iwindplus.mgt.domain.vo.power.PositionBaseCheckedVO;
import com.iwindplus.mgt.domain.vo.power.PositionExtendVO;
import com.iwindplus.mgt.domain.vo.power.PositionPageVO;
import com.iwindplus.mgt.domain.vo.power.PositionVO;
import com.iwindplus.mgt.server.mapper.power.PositionMapper;
import com.iwindplus.mgt.server.model.power.PositionDO;
import com.iwindplus.mgt.server.service.power.PositionRoleService;
import com.iwindplus.mgt.server.service.power.PositionService;
import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 职位业务层接口实现类.
 *
 * @author zengdegui
 * @since 2018/9/1
 */
@Service
@CacheConfig(cacheNames = {"position"})
@Transactional(rollbackFor = Exception.class)
public class PositionServiceImpl extends JoinCrudRepository<PositionMapper, PositionDO> implements PositionService {

    @Resource
    private SerialNumManager serialNumManager;

    @Resource
    private PositionRoleService positionRoleService;

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"position"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
        }
    )
    @Override
    public boolean save(PositionSaveDTO entity) {
        entity.setStatus(EnableStatusEnum.ENABLE);
        entity.setBuildInFlag(Boolean.FALSE);
        this.getNameIsExist(entity.getName().trim(), entity.getDepartmentId(), entity.getOrgId());
        if (CharSequenceUtil.isBlank(entity.getCode())) {
            entity.setCode(this.serialNumManager.getSerialNum(MgtCodePrefixEnum.POSITION_PREFIX.getValue()));
        }
        this.getCodeIsExist(entity.getCode().trim(), entity.getDepartmentId(), entity.getOrgId());
        entity.setSeq(this.getNextSeq(entity.getDepartmentId(), entity.getOrgId()));
        final PositionDO model = BeanUtil.copyProperties(entity, PositionDO.class);
        super.save(model);
        entity.setId(model.getId());
        this.positionRoleService.saveBatchRole(model.getId(), entity.getRoleIds());
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"position"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
        }
    )
    @Override
    public List<PositionVO> saveBatchInit(List<PositionDTO> entities) {
        List<PositionVO> resultList = new ArrayList<>(10);
        AtomicReference<Integer> seq = new AtomicReference<>();
        AtomicBoolean flag = new AtomicBoolean(true);
        List<PositionDTO> saveList = new ArrayList<>(10);
        List<PositionDTO> existList = new ArrayList<>(10);
        entities.forEach(entity -> {
            final PositionDO data = super.getOne(Wrappers.lambdaQuery(PositionDO.class)
                .eq(PositionDO::getName, entity.getName())
                .eq(PositionDO::getDepartmentId, entity.getDepartmentId())
                .eq(PositionDO::getOrgId, entity.getOrgId()));
            if (Objects.isNull(data)) {
                if (flag.get()) {
                    seq.set(this.getNextSeq(entity.getDepartmentId(), entity.getOrgId()));
                    flag.set(false);
                }
                entity.setSeq(seq.getAndSet(seq.get() + 1));
                saveList.add(entity);
            } else {
                final PositionDTO dto = BeanUtil.copyProperties(data, PositionDTO.class);
                existList.add(dto);
            }
        });
        if (CollUtil.isNotEmpty(saveList)) {
            final List<PositionDO> doList = BeanUtil.copyToList(saveList, PositionDO.class);
            super.saveBatch(doList, DEFAULT_BATCH_SIZE);
            final List<PositionVO> voList = BeanUtil.copyToList(doList, PositionVO.class);
            resultList.addAll(voList);
        }
        if (CollUtil.isNotEmpty(existList)) {
            final List<PositionVO> voList = BeanUtil.copyToList(existList, PositionVO.class);
            resultList.addAll(voList);
        }
        return resultList;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"position"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
        }
    )
    @Override
    public boolean removeByIds(List<Long> ids) {
        List<PositionDO> list = super.listByIds(ids);
        if (CollUtil.isEmpty(list)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        boolean match = list.stream().anyMatch(PositionDO::getBuildInFlag);
        if (Boolean.TRUE.equals(match)) {
            throw new BizException(BizCodeEnum.HAS_BUILD_IN_DATA);
        }
        this.positionRoleService.removeByRoleIds(ids);
        super.removeByIds(ids);
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"position"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
        }
    )
    @Override
    public boolean edit(PositionEditDTO entity) {
        PositionDO data = super.getById(entity.getId());
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        // 校验名称是否存在
        if (CharSequenceUtil.isNotBlank(entity.getName()) && !CharSequenceUtil.equals(data.getName(), entity.getName().trim())) {
            this.getNameIsExist(entity.getName().trim(), data.getDepartmentId(), data.getOrgId());
        }
        if (CharSequenceUtil.isNotBlank(entity.getCode()) && !CharSequenceUtil.equals(data.getCode(), entity.getCode().trim())) {
            this.getCodeIsExist(entity.getCode().trim(), data.getDepartmentId(), data.getOrgId());
        }
        if (Objects.isNull(entity.getVersion())) {
            entity.setVersion(data.getVersion());
        }
        final PositionDO model = BeanUtil.copyProperties(entity, PositionDO.class);
        super.updateById(model);
        this.positionRoleService.editBatchRole(entity.getId(), entity.getRoleIds());
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"position"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
        }
    )
    @Override
    public boolean editStatus(Long id, EnableStatusEnum status) {
        PositionDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        if (status.equals(data.getStatus())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        PositionDO param = new PositionDO();
        param.setId(id);
        param.setStatus(status);
        param.setVersion(data.getVersion());
        super.updateById(param);
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"position"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
        }
    )
    @Override
    public boolean editBuildIn(Long id, Boolean buildInFlag) {
        PositionDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (buildInFlag.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        PositionDO param = new PositionDO();
        param.setId(id);
        param.setBuildInFlag(buildInFlag);
        param.setVersion(data.getVersion());
        super.updateById(param);
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"position"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
        }
    )
    @Override
    public Map<Long, Long> editInitToDepartment(Long orgId, Map<Long, Long> departmentIdMap, List<PositionDTO> entities) {
        Map<Long, Long> idMap = new HashMap<>(16);
        if (CollUtil.isEmpty(entities)) {
            return Collections.emptyMap();
        }
        final List<PositionDO> paramList = BeanUtil.copyToList(entities, PositionDO.class);
        final List<PositionDO> oldList = BeanUtil.copyToList(entities, PositionDO.class);
        this.buildInitList(orgId, departmentIdMap, paramList);
        final List<PositionDTO> dtoList = BeanUtil.copyToList(paramList, PositionDTO.class);
        final List<PositionVO> voList = this.saveBatchInit(dtoList);
        final List<PositionDO> newList = BeanUtil.copyToList(voList, PositionDO.class);
        this.buildIdMap(idMap, oldList, newList);
        return idMap;
    }

    @Override
    public IPage<PositionPageVO> page(PositionSearchDTO entity) {
        PageDTO<PositionDO> page = new PageDTO<>(entity.getCurrent(), entity.getSize());
        page.setOptimizeCountSql(Boolean.FALSE);
        page.setOptimizeJoinOfCountSql(Boolean.FALSE);
        final LambdaQueryWrapper<PositionDO> queryWrapper = Wrappers.lambdaQuery(PositionDO.class)
            .eq(PositionDO::getDepartmentId, entity.getDepartmentId());
        if (Objects.nonNull(entity.getStatus())) {
            queryWrapper.eq(PositionDO::getStatus, entity.getStatus());
        }
        if (CharSequenceUtil.isNotBlank(entity.getCode())) {
            queryWrapper.eq(PositionDO::getCode, entity.getCode().trim());
        }
        if (CharSequenceUtil.isNotBlank(entity.getName())) {
            queryWrapper.eq(PositionDO::getName, entity.getName().trim());
        }
        // 排序
        List<OrderItem> orders = page.getOrders();
        if (CollUtil.isEmpty(orders)) {
            orders = new ArrayList<>(10);
            OrderItem item = OrderItem.desc(CommonConstant.DbConstant.MODIFIED_TIME);
            orders.add(item);
        }
        orders.forEach(order -> {
            String column = order.getColumn();
            String underline = CharSequenceUtil.toUnderlineCase(column);
            order.setColumn(underline);
        });
        page.setOrders(orders);
        queryWrapper.select(PositionDO::getId, PositionDO::getCreatedTime, PositionDO::getCreatedBy, PositionDO::getModifiedTime,
            PositionDO::getModifiedBy,
            PositionDO::getVersion, PositionDO::getStatus, PositionDO::getCode, PositionDO::getName, PositionDO::getBuildInFlag,
            PositionDO::getDepartmentId);
        final PageDTO<PositionDO> modelPage = super.page(page, queryWrapper);
        return modelPage.convert(model -> BeanUtil.copyProperties(model, PositionPageVO.class));
    }

    @Cacheable(key = "#root.methodName + '_' + #p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public PositionExtendVO getDetailExtend(Long id) {
        return super.baseMapper.selectDetailById(id);
    }

    @Cacheable(key = "#root.methodName + '_' + #p0 + '_' + #p1", condition = "#p1 != null", unless = "#result == null")
    @Override
    public List<PositionBaseCheckedVO> listByUserId(Long orgId, Long userId) {
        List<PositionBaseCheckedVO> allList = super.baseMapper.selectListByOrgId(orgId);
        if (CollUtil.isEmpty(allList)) {
            return null;
        }
        if (Objects.nonNull(userId)) {
            List<PositionBaseCheckedVO> checkedList = super.baseMapper.selectListByUserId(orgId, userId);
            if (CollUtil.isNotEmpty(checkedList)) {
                allList = this.listWithChecked(allList, checkedList);
            }
        }
        return allList;
    }

    private void getNameIsExist(String name, Long departmentId, Long orgId) {
        final LambdaQueryWrapper<PositionDO> queryWrapper = Wrappers.lambdaQuery(PositionDO.class)
            .eq(PositionDO::getName, name)
            .eq(PositionDO::getDepartmentId, departmentId)
            .eq(PositionDO::getOrgId, orgId);
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (result) {
            throw new BizException(MgtCodeEnum.NAME_EXIST);
        }
    }

    private void getCodeIsExist(String code, Long departmentId, Long orgId) {
        final LambdaQueryWrapper<PositionDO> queryWrapper = Wrappers.lambdaQuery(PositionDO.class)
            .eq(PositionDO::getCode, code)
            .eq(PositionDO::getDepartmentId, departmentId)
            .eq(PositionDO::getOrgId, orgId);
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (Boolean.TRUE.equals(result)) {
            throw new BizException(MgtCodeEnum.CODE_EXIST);
        }
    }

    /**
     * 查询下一个排序号.
     *
     * @param departmentId 部门主键
     * @param orgId        组织主键
     * @return Integer
     */
    private Integer getNextSeq(Long departmentId, Long orgId) {
        QueryWrapper<PositionDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PositionDO::getDepartmentId, departmentId);
        queryWrapper.lambda().eq(PositionDO::getOrgId, orgId);
        queryWrapper.select("max(seq) as seq");
        Function<Object, Integer> function = val -> Integer.valueOf(val.toString());
        Integer data = super.getObj(queryWrapper, function);
        return Optional.ofNullable(data).map(x -> x + 1).orElse(1);
    }

    private List<PositionBaseCheckedVO> listWithChecked(List<PositionBaseCheckedVO> allList, List<PositionBaseCheckedVO> checkedList) {
        return allList.stream().peek(map -> checkedList.stream()
                .filter(m -> Objects.equals(m.getId(), map.getId())).forEach(m -> map.setChecked(m.getChecked())))
            .collect(Collectors.toCollection(ArrayList::new));
    }

    private void buildInitList(Long orgId, Map<Long, Long> departmentIdMap, List<PositionDO> entities) {
        entities.forEach(entity -> {
            entity.setId(null);
            entity.setVersion(0);
            entity.setDepartmentId(departmentIdMap.get(entity.getDepartmentId()));
            entity.setOrgId(orgId);
            entity.setRemark(MgtConstant.REMARK_INIT);
        });
        entities.removeIf(m -> Objects.isNull(m.getDepartmentId()) || Objects.isNull(m.getOrgId()));
    }

    private void buildIdMap(Map<Long, Long> idMap, List<PositionDO> oldList, List<PositionDO> newList) {
        oldList.forEach(oldData -> newList.forEach(newData -> {
            if (oldData.getName().equals(newData.getName())) {
                idMap.put(oldData.getId(), newData.getId());
            }
        }));
    }
}
